<template>
  <div class="user">
    <!-- 面包屑区域 -->
    <BreadCrumb>用户管理</BreadCrumb>
    <div class="content">
      <!-- 卡片区域 -->
      <el-card>
        <!-- 搜索与添加区域 row(行)和 col(列) 是栅格布局-->
        <el-row :gutter="20">
          <el-col :span="10">
            <el-input placeholder="Please input" size="large" v-model="input"  class="input-with-select" @keydown.enter="searchUser">
              <template #prepend>
                <el-select v-model="select" style="width: 135px">
                  <el-option label="用户 ID" value="1" />
                  <el-option label="用户名关键词" value="2" />
                  <el-option label="是否管理员" value="3" />
                </el-select>
              </template>
              <template #append>
                <el-button icon="el-icon-search" @click="searchUser"/>
              </template>
            </el-input>
          </el-col>
          <el-col :span="5">
            <el-button type="primary" size="large" @click="AddDialogVisible=true">添加</el-button>
          </el-col>
        </el-row>
        <!-- 用户列表区域 -->
        <el-table :data="data" border stripe>
          <el-table-column type="index" label="#" align="center"></el-table-column>
          <el-table-column prop="id" label="id" align="center"/>
          <el-table-column prop="username" label="username" align="center"/>
          <el-table-column prop="password" label="password" align="center"/>
          <el-table-column prop="is_admin" label="is_admin" align="center"/>
          <el-table-column label="操作" align="center">
            <template #default="scope">
              <el-button  icon="el-icon-edit"  type="success" @click="handleEdit(scope.row)" :disabled="userStore.user.is_admin==='is' ? false : true">修改</el-button>
              <el-button icon="el-icon-delete" type="danger" @click="handleDelete(scope.row)" :disabled="userStore.user.is_admin==='is' ? false : true">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <!-- 添加用户的对话框 -->
    <el-dialog v-model="AddDialogVisible" title="添加用户" width="40%" draggable @close="addDialogClosed">
      <!-- 表单区域 -->
      <el-form ref="addFormRef" :model="addForm" :rules="addRules" label-width="100px" size="large">
        <el-form-item label="用户名" prop="username">
          <el-input v-model.trim="addForm.username" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model.trim="addForm.password" />
        </el-form-item>
        <el-form-item label="是否管理员" prop="is_admin">
          <!-- <el-input v-model.trim="addForm.is_admin" /> -->
          <el-select v-model="addForm.is_admin" placeholder="请选择">
            <el-option label="is" value="is" />
            <el-option label="no" value="no" />
          </el-select>
        </el-form-item>
      </el-form>
      <!-- 按钮区域 -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="AddDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addUser(addFormRef)">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 修改用户的对话框 -->
    <el-dialog v-model="EditDialogVisible" title="修改用户" width="40%" draggable @close="editDialogClosed">
      <!-- 表单区域 -->
      <el-form ref="editFormRef" :model="editForm" :rules="editRules" label-width="100px" size="large">
        <el-form-item label="id">
          <el-input v-model="editForm.id" disabled/>
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model.trim="editForm.username"/>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model.trim="editForm.password" />
        </el-form-item>
        <el-form-item label="是否管理员" prop="is_admin">
          <!-- <el-input v-model.trim="editForm.is_admin" /> -->
          <el-select v-model="editForm.is_admin" placeholder="请选择">
            <el-option label="is" value="is" />
            <el-option label="no" value="no" />
          </el-select>
        </el-form-item>
      </el-form>
      <!-- 按钮区域 -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="EditDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="editUser(editFormRef)">确定</el-button>
        </span>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import {useUserStore} from '@/store/userStore.js'
import BreadCrumb from '@/components/common/BreadCrumb.vue'
import { ElMessageBox } from 'element-plus'
import {getAllUsers,updateUser,getUserById,register,deleteUser,
  getUserByNameKey,getUserByIsAdmin
} from '@/network/user.js'
import { onMounted, reactive, ref } from 'vue';
import { messageApi } from '../api/global';

//* 变量声明
const userStore = useUserStore()
let data = ref([]) // 用户信息数据
const select = ref('1')  // 下拉选择
const input = ref('') // 文本输入框值 -- 
const AddDialogVisible = ref(false)  // 控制添加对话框的显示和隐藏
const addFormRef = ref(null)  // 添加用户对话框的引用
let addForm = reactive({
  username: '',
  password: '',
  is_admin: ''
}) // 添加用户的表单数据 ---
const EditDialogVisible = ref(false)  // 控制修改对话框的显示和隐藏
let editForm = ref({})// 修改用户的表单数据
const editFormRef = ref(null)  // 修改用户对话框的引用
// 添加用户的表单规则
const addRules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 1, max: 10, message: '用户名的长度在1~10个字符之间', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 3, max: 16, message: '密码的长度在3~16个字符之间', trigger: 'blur' }
  ],
  is_admin: [
    { required: true, message: '请输入是否管理员', trigger: 'blur' },
    { max: 2, message: '只能填 is 或 no', trigger: 'blur' }
  ],
})
// 修改用户的表单规则
const editRules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 1, max: 10, message: '用户名的长度在1~10个字符之间', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 3, max: 16, message: '密码的长度在3~16个字符之间', trigger: 'blur' }
  ],
  is_admin: [
    { required: true, message: '请输入是否管理员', trigger: 'blur' },
    { max: 2, message: '只能填 is 或 no', trigger: 'blur' }
  ],
})


//* 事件处理

// 获取所有用户信息
const getUsers = async () => {
  const { data: res} = await getAllUsers()
  data.value = res.data
}

// 查询用户
const searchUser = async () => {
  // 用户 id 查询
  if (select.value === "1") {
    messageApi().closeAll()
    if (input.value === '' ) return getUsers()
    const {data:res} = await getUserById(input.value)
    if (res.code !== 200) return messageApi('error', res.msg)
    data.value = []
    data.value.push(res.data)
  }
  // 用户名模糊查询
  if (select.value === "2") {
    const {data:res} = await getUserByNameKey({userkey: input.value})
    if (res.code !== 200) return messageApi('error', '查询失败！')
    data.value = res.data
  }
  // 是否管理员查询
  if (select.value === "3") {
    messageApi().closeAll()
    if (input.value === '' ) return getUsers()
    if (input.value !== 'no' && input.value !== 'is') return messageApi('warning', '请输入 is 或 no！')
    const {data:res} = await getUserByIsAdmin(input.value)
    if (res.code !== 200) return messageApi('error', '查询失败！')
    data.value = res.data
  }
}

// 添加用户
const addUser = async (addRef) => {
  // 先进行预校验
  await addRef.validate( async valid => {
    if (!valid) return Error;
    const {data: res} = await register(addForm)
    if (res.code !== 200) return messageApi('error', res.msg)
    messageApi('success', res.msg)
    getUsers()
    AddDialogVisible.value = false
  })
}
// 添加用户对话框的关闭事件
const addDialogClosed = () => {
  addFormRef.value.resetFields()
}

// 显示修改用户信息的对话框
const handleEdit = async (row) => {
  const {data: res} = await getUserById(row.id)
  if (res.code !== 200) return messageApi('error', '获取用户信息失败！')
  editForm.value = res.data
  EditDialogVisible.value = true
}

// 确认修改用户信息
const editUser = async (editRef) => {
  // 先进行预校验
  await editRef.validate(async valid => {
    if (!valid) return Error;
    // 发起修改请求
    console.log(editForm.value);
    const {data: res} = await updateUser(editForm.value)
    if (res.code !== 200) return messageApi('error', res.msg);
    getUsers()
    messageApi('success', res.msg)
    EditDialogVisible.value = false
  })
  

}

// 修改用户对话框的关闭事件
const editDialogClosed = () => {
  editFormRef.value.resetFields()
}

// 删除用户
const handleDelete = async (row) => {
  try{
    await ElMessageBox.confirm(`确认删除读者 “${row.username}” 吗？`, '警告', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })
    // 发起删除用户的请求
    const {data: res} = await deleteUser(row.id);
    if (res.code !== 200) return messageApi('error', '删除用户失败！')
    messageApi('success', res.msg)
    getUsers()
  }catch(e) {
    messageApi('info', '已取消')
  }
}

onMounted(() => {
  getUsers()
})

</script>

<style lang="less" scoped>
.user {
  height: 100%;
  width: 85%;
  background-color: #eaedf1;
  // overflow: scroll;

}
.content {
  width: 100%;
  // height: 600px;
  margin: 0 15px;
  background: #fff;
  overflow: auto;
  width:  1300px;

  .el-card {
    width: 100%;
  }
  .el-table {
    width: 100%
  }
  .el-row {
    margin-bottom: 10px;
  }
}

.input-with-select .el-input-group__prepend {
  background-color: var(--el-fill-color-blank);
}

</style>